package com.chyblog.demo.clients;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DiscoveryClientExample {

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 使用自己的服务做远程服务名
     */
    @Value("${spring.application.name}")
    private String remoteServiceName;

    public String serviceUrl() {
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances(remoteServiceName);
        if (serviceInstances != null && !serviceInstances.isEmpty()) {
            return String.valueOf(serviceInstances.get(0).getUri());
        }
        return null;
    }
}
